<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>synchronized关键字 | Reality</title><meta name="keywords" content="Java内存模型,synchronized"><meta name="author" content="dtyy"><meta name="copyright" content="dtyy"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="Java在设计之初就支持多线程，而synchronized作为Java关键字，被Java语言原生支持，是最基本的互斥同步手段。 一句话概括synchronized的作用：能够保证在同一时刻最多只有一个线程执行该段代码，以达到保证并发安全的效果。  一、synchronized的两种用法：对象锁和类锁1.1 对象锁对象锁包括同步代码块锁和普通方法锁。  同步代码块形式 对于同步代码块，如果指定th">
<meta property="og:type" content="article">
<meta property="og:title" content="synchronized关键字">
<meta property="og:url" content="https://dtyytop.gitee.io/2020/05/15/devnotes/zhi-mian-java/bing-fa/bing-fa-he-xin/2.2-synchronized-guan-jian-zi/index.html">
<meta property="og:site_name" content="Reality">
<meta property="og:description" content="Java在设计之初就支持多线程，而synchronized作为Java关键字，被Java语言原生支持，是最基本的互斥同步手段。 一句话概括synchronized的作用：能够保证在同一时刻最多只有一个线程执行该段代码，以达到保证并发安全的效果。  一、synchronized的两种用法：对象锁和类锁1.1 对象锁对象锁包括同步代码块锁和普通方法锁。  同步代码块形式 对于同步代码块，如果指定th">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222615.jpg">
<meta property="article:published_time" content="2020-05-15T15:28:04.000Z">
<meta property="article:modified_time" content="2021-05-25T23:47:39.085Z">
<meta property="article:author" content="dtyy">
<meta property="article:tag" content="Java内存模型">
<meta property="article:tag" content="synchronized">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222615.jpg"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://dtyytop.gitee.io/2020/05/15/devnotes/zhi-mian-java/bing-fa/bing-fa-he-xin/2.2-synchronized-guan-jian-zi/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><meta/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"prismjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: true
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50,"languages":{"author":"作者: dtyy","link":"链接: ","source":"来源: Reality","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'synchronized关键字',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2021-05-26 07:47:39'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const fontSizeVal = saveToLocal.get('global-font-size')
    if (fontSizeVal !== undefined) {
      document.documentElement.style.setProperty('--global-font-size', fontSizeVal + 'px')
    }
    })(window)</script><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="Reality" type="application/atom+xml">

<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
</head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">95</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">28</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">16</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 清单</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/gallery/"><i class="fa-fw fas fa-images"></i><span> 图片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222615.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">Reality</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 清单</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/gallery/"><i class="fa-fw fas fa-images"></i><span> 图片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">synchronized关键字</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2020-05-15T15:28:04.000Z" title="发表于 2020-05-15 23:28:04">2020-05-15</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2021-05-25T23:47:39.085Z" title="更新于 2021-05-26 07:47:39">2021-05-26</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/">并发编程</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/Java%E5%86%85%E5%AD%98%E6%A8%A1%E5%9E%8B/">Java内存模型</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">2.6k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>8分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="synchronized关键字"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><blockquote>
<p>Java在设计之初就支持多线程，而synchronized作为Java关键字，被Java语言原生支持，是最基本的互斥同步手段。 一句话概括synchronized的作用：能够保证在同一时刻最多只有一个线程执行该段代码，以达到保证并发安全的效果。</p>
</blockquote>
<h2 id="一、synchronized的两种用法：对象锁和类锁"><a href="#一、synchronized的两种用法：对象锁和类锁" class="headerlink" title="一、synchronized的两种用法：对象锁和类锁"></a>一、synchronized的两种用法：对象锁和类锁</h2><h3 id="1-1-对象锁"><a href="#1-1-对象锁" class="headerlink" title="1.1 对象锁"></a>1.1 对象锁</h3><p>对象锁包括同步代码块锁和普通方法锁。</p>
<ul>
<li>同步代码块形式 对于同步代码块，如果指定this，表示锁对象是当前实例对象；如果业务较复杂，可以自定义锁对象。开发时通常采用并发工具类辅助实现，而不是自定义锁对象，因为分析不到位，容易导致线程安全问题。</li>
<li>普通方法形式 普通方法锁即在普通方法上加上synchronized关键字修饰，默认锁对象是this当前实例对象。synchronized可以加在run()方法上，也可以加在自定义方法上。</li>
</ul>
<h3 id="1-2-类锁"><a href="#1-2-类锁" class="headerlink" title="1.2 类锁"></a>1.2 类锁</h3><p>Java类可能有很多个对象，但是只会有一个Class对象。<strong>类锁，指的是Class对象的锁。</strong></p>
<p>类锁只能在同一时刻被一个对象拥有，其他线程竞争的话会被阻塞。此时，即使有多个Runnable实例，Class对象仍然只有一个，能够保证线程安全。而<u>对象锁只能保证在一个Runnable实例下线程同步。</u></p>
<p>类锁包括静态方法锁和同步代码块锁。</p>
<ul>
<li>静态方法锁 – synchronized关键字加在static方法上。</li>
<li>同步代码块锁 – 同步代码块指定锁对象是类.class。</li>
</ul>
<h3 id="1-3-调试技巧-–-查看线程生命周期"><a href="#1-3-调试技巧-–-查看线程生命周期" class="headerlink" title="1.3 调试技巧 – 查看线程生命周期"></a>1.3 调试技巧 – 查看线程生命周期</h3><p>首先给代码打断点，在Debugger标签下切换想要查看的线程，通过Thread类查看JVM线程状态。我们可以看到当前Thread-1处于RUNNABLE状态，Thread-0处于BLOCKED状态。 </p>
<p><img src="https://gitee.com/dtyytop/blogimage/raw/master/img/20210519230827.png" alt="image-20210519230826954"></p>
<h3 id="1-4-多线程访问同步方法的7种情况"><a href="#1-4-多线程访问同步方法的7种情况" class="headerlink" title="1.4 多线程访问同步方法的7种情况"></a>1.4 多线程访问同步方法的7种情况</h3><ol>
<li>两个线程同时访问一个对象的同步方法</li>
</ol>
<p>两个线程访问的是同一把锁，一个线程占有锁，另一个线程只能等待。</p>
<ol start="2">
<li>两个线程访问的是两个对象的同步方法</li>
</ol>
<p>两个线程采用的锁对象不同，同步不起作用。两个<strong>对象指的是创建线程时送入的Runnable实例instance。</strong></p>
<ol start="3">
<li>两个线程访问的是synchronized静态方法</li>
</ol>
<p>虽然Runnable实例是不同的，但只要方法是静态的，两个线程竞争的是同一把锁，锁对象是类的Class对象。</p>
<ol start="4">
<li>两个线程分别访问同步方法和非同步方法</li>
</ol>
<p>非同步方法不受到影响，因此可以同时运行。</p>
<ol start="5">
<li>两个线程访问同一个对象的不同的普通同步方法</li>
</ol>
<p>synchronized修饰普通方法默认的加锁对象是this–当前对象，因此访问同一对象的不同普通同步方法时，仍然是线程安全的。</p>
<ol start="6">
<li>两个线程分别访问静态synchronized和非静态synchronized方法（需要注意的情况）</li>
</ol>
<p>synchronized修饰static方法时，锁对象是类的Class对象，而synchronized修饰普通方法时，锁对象是当前类对象。两者的锁不同，互不冲突。因此仍然可以同时运行。</p>
<ol start="7">
<li>方法抛异常后，会释放锁</li>
</ol>
<p><u>对于synchronized同步，方法抛出异常后自动释放锁，而Lock锁必须进行显式释放。</u></p>
<blockquote>
<p>对于同步是否生效，核心在于是否竞争同一把锁！</p>
</blockquote>
<ol start="8">
<li>同步方法中调用了非同步方法的情况</li>
</ol>
<p>同步方法A中调用了非同步方法B可以通过两种情况分析。</p>
<ul>
<li>每个线程对方法B的调用都是通过方法A来进行时，此时线程安全，方法B可以设置为私有方法。</li>
<li>如果方法B由public方法修饰，线程可以通过方法A调用方法B，也可以通过其他途径调用方法B，例如直接调用，此时是线程不安全的。</li>
</ul>
<h4 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h4><ol>
<li>一把锁只能同时被一个线程所持有，没有拿到锁的线程只能等待。</li>
<li>每个实例都对应有自己的一把锁，不同实例之间互不影响。锁对象是Class对象，所有实例共用同一把锁。实例锁和类锁不相互影响。</li>
<li>无论方法正常执行结束，还是抛出异常，都会释放锁。</li>
</ol>
<h2 id="二、synchronized的性质"><a href="#二、synchronized的性质" class="headerlink" title="二、synchronized的性质"></a>二、synchronized的性质</h2><h3 id="2-1-可重入性质"><a href="#2-1-可重入性质" class="headerlink" title="2.1 可重入性质"></a>2.1 可重入性质</h3><p>可重入，指的是同一个线程的外层函数获得锁之后，内层函数可以直接再次获取该锁。不可重入，则指的是如果一个线程获取锁，想再次获取该锁，必须释放这把锁，重新获取。Java中的可重入锁有两种，分别是synchronized和ReentrantLock。</p>
<p><strong>可重入锁的好处有避免死锁、提升封装性。</strong><u>假设线程T要同时访问两个synchronized方法A和B，如果不具备可重入性，在AB是同一把锁时，线程调用A后无法调用B，就会导致死锁。可重入锁避免了反复的加锁解锁，便于封装。</u></p>
<p>synchronized的粒度（加锁的范围）是线程而不是调用。</p>
<h3 id="2-2-不可中断性质"><a href="#2-2-不可中断性质" class="headerlink" title="2.2 不可中断性质"></a>2.2 不可中断性质</h3><p>不可中断，是指一旦锁被某线程获得，其他线程想要获得该锁只能等待该线程释放锁。</p>
<h2 id="三、synchronized底层原理"><a href="#三、synchronized底层原理" class="headerlink" title="三、synchronized底层原理"></a>三、synchronized底层原理</h2><h3 id="3-1-内置锁与等价Lock形式代码"><a href="#3-1-内置锁与等价Lock形式代码" class="headerlink" title="3.1 内置锁与等价Lock形式代码"></a>3.1 内置锁与等价Lock形式代码</h3><p>每个Java对象都可以用作一个实现同步的锁，成为内置锁或者监视器锁（monitor lock）。线程在进入同步代码块之前会自动获取锁，并且在退出同步代码块时自动释放锁，无论是通过正常路径退出，还是通过代码块中抛出异常退出。</p>
<p>获得内置锁的唯一途径就是进入由这个锁保护的同步方法或代码块。</p>
<p>等效Lock形式代码</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">Lock</span> lock <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ReentrantLock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token keyword">public</span> <span class="token keyword">synchronized</span> <span class="token keyword">void</span> <span class="token function">method1</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"synchronized锁"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token keyword">public</span> <span class="token keyword">void</span> method2 <span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    lock<span class="token punctuation">.</span><span class="token function">lock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">try</span> <span class="token punctuation">{</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"lock形式锁"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span> <span class="token keyword">finally</span> <span class="token punctuation">{</span>
        lock<span class="token punctuation">.</span><span class="token function">unlock</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h3 id="3-2-可重入原理"><a href="#3-2-可重入原理" class="headerlink" title="3.2 可重入原理"></a>3.2 可重入原理</h3><p>可重入是通过monitor加锁次数计数器来实现的。JVM负责跟踪对象被加锁的次数。线程第一次给对象加锁，计数变为1；重入获取锁，计数递增；任务离开时，计数减1。</p>
<h4 id="深入JVM看字节码–仅同步代码块"><a href="#深入JVM看字节码–仅同步代码块" class="headerlink" title="深入JVM看字节码–仅同步代码块"></a>深入JVM看字节码–仅同步代码块</h4><p>从JVM 规范中可以看到Synchonized在JVM里的实现原理， JVM基于进入和退出 Monitor对象来实现方法同步和代码块同步， 但两者的实现细节不一样。 <strong>代码块同步是使用monitorenter和monitorexit指令实现的</strong>， 而方法同步是使用另外一种方式实现的， 细节在JVM规范里并没有详细说明。 但是，方法的同步同样可以使用这两个指令来实现。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java">javac <span class="token class-name">DecompileSynchronizedCode</span><span class="token punctuation">.</span>java
javap <span class="token operator">-</span>verbose <span class="token class-name">DecompileSynchronizedCode</span><span class="token punctuation">.</span><span class="token keyword">class</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>简单的同步代码块源码</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">DecompileSynchronizedObject</span> <span class="token punctuation">{</span>
    <span class="token keyword">private</span> <span class="token class-name">Object</span> object <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Object</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">insert</span><span class="token punctuation">(</span><span class="token class-name">Thread</span> thread<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">synchronized</span> <span class="token punctuation">(</span>object<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>通过javap查看反编译字节码文件</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">insert</span><span class="token punctuation">(</span><span class="token class-name"><span class="token namespace">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span></span>Thread</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
descriptor<span class="token operator">:</span> <span class="token punctuation">(</span><span class="token class-name">Ljava</span><span class="token operator">/</span>lang<span class="token operator">/</span><span class="token class-name">Thread</span><span class="token punctuation">;</span><span class="token punctuation">)</span><span class="token class-name">V</span>
flags<span class="token operator">:</span> ACC_PUBLIC
<span class="token class-name">Code</span><span class="token operator">:</span>
  stack<span class="token operator">=</span><span class="token number">2</span><span class="token punctuation">,</span> locals<span class="token operator">=</span><span class="token number">4</span><span class="token punctuation">,</span> args_size<span class="token operator">=</span><span class="token number">2</span>
     <span class="token number">0</span><span class="token operator">:</span> aload_0
     <span class="token number">1</span><span class="token operator">:</span> getfield      #<span class="token number">3</span>                  <span class="token comment">// Field object:Ljava/lang/Object;</span>
     <span class="token number">4</span><span class="token operator">:</span> dup
     <span class="token number">5</span><span class="token operator">:</span> astore_2
     <span class="token number">6</span><span class="token operator">:</span> monitorenter        <span class="token comment">// 进入同步方法</span>
     <span class="token number">7</span><span class="token operator">:</span> aload_2 
     <span class="token number">8</span><span class="token operator">:</span> monitorexit         <span class="token comment">// 退出同步方法</span>
     <span class="token number">9</span><span class="token operator">:</span> <span class="token keyword">goto</span>          <span class="token number">17</span>
    <span class="token number">12</span><span class="token operator">:</span> astore_3
    <span class="token number">13</span><span class="token operator">:</span> aload_2
    <span class="token number">14</span><span class="token operator">:</span> monitorexit         <span class="token comment">// 退出同步方法</span>
    <span class="token number">15</span><span class="token operator">:</span> aload_3
    <span class="token number">16</span><span class="token operator">:</span> athrow
    <span class="token number">17</span><span class="token operator">:</span> <span class="token keyword">return</span>
  <span class="token class-name">Exception</span> table<span class="token operator">:</span>
     from    <span class="token keyword">to</span>  <span class="token namespace">target</span> type
         <span class="token number">7</span>     <span class="token number">9</span>    <span class="token number">12</span>   any
        <span class="token number">12</span>    <span class="token number">15</span>    <span class="token number">12</span>   any
  <span class="token class-name">LineNumberTable</span><span class="token operator">:</span>
    line <span class="token number">11</span><span class="token operator">:</span> <span class="token number">0</span>
    line <span class="token number">13</span><span class="token operator">:</span> <span class="token number">7</span>
    line <span class="token number">14</span><span class="token operator">:</span> <span class="token number">17</span>
  <span class="token class-name">StackMapTable</span><span class="token operator">:</span> number_of_entries <span class="token operator">=</span> <span class="token number">2</span>
    frame_type <span class="token operator">=</span> <span class="token number">255</span> <span class="token comment">/* full_frame */</span>
      offset_delta <span class="token operator">=</span> <span class="token number">12</span>
      locals <span class="token operator">=</span> <span class="token punctuation">[</span> <span class="token keyword">class</span> com<span class="token operator">/</span>lzp<span class="token operator">/</span>java<span class="token operator">/</span>concurrent<span class="token operator">/</span>core<span class="token operator">/</span>synchronize<span class="token operator">/</span><span class="token class-name">DecompileSynchronizedObject</span><span class="token punctuation">,</span> <span class="token keyword">class</span> java<span class="token operator">/</span>lang<span class="token operator">/</span><span class="token class-name">Thread</span><span class="token punctuation">,</span> <span class="token keyword">class</span> java<span class="token operator">/</span>lang<span class="token operator">/</span><span class="token class-name">Object</span> <span class="token punctuation">]</span>
      stack <span class="token operator">=</span> <span class="token punctuation">[</span> <span class="token keyword">class</span> java<span class="token operator">/</span>lang<span class="token operator">/</span><span class="token class-name">Throwable</span> <span class="token punctuation">]</span>
    frame_type <span class="token operator">=</span> <span class="token number">250</span> <span class="token comment">/* chop */</span>
      offset_delta <span class="token operator">=</span> <span class="token number">4</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>可以看到synchronized同步代码块是通过monitorenter和monitorexit命令来控制的，并且两者不是一一对应关系，因为退出同步代码块包括正常退出和抛异常退出。</p>
<h4 id="理解monitorenter和monitorexit指令"><a href="#理解monitorenter和monitorexit指令" class="headerlink" title="理解monitorenter和monitorexit指令"></a>理解monitorenter和monitorexit指令</h4><p>每个Java对象都有一个对象头，synchronized<u>锁标识就存储在对象头中</u>。monitorenter和monitorexit命令在执行时使对象锁计数加1和减1。一个monitor锁同一时间只能被一个线程获得。线程在尝试获得对象monitor锁所有权的时候，会发生下面3种情况：（1）如果monitor计数器为0，表示该锁未被获得，线程会立即获得锁，monitor计数器加1。（2）如果线程已经拿到monitor锁所有权，并且重入，monitor计数器累加。（3）如果其他线程已经获取到monitor锁，此时尝试获取，只能进入阻塞状态。直到monitor计数器变为0，才会再次尝试获取。</p>
<p>monitorexit用来释放锁的所有权，前提是线程拥有锁。释放过程就是将monitor计数器减1，如果减完之后值为0，表示当前线程不再持有monitor锁，其他线程可尝试获取该锁。</p>
<h3 id="3-3-可见性原理"><a href="#3-3-可见性原理" class="headerlink" title="3.3 可见性原理"></a>3.3 可见性原理</h3><p>了解Java内存模型，才能理解可见性原理。 </p>
<p><img src="https://gitee.com/dtyytop/blogimage/raw/master/img/20210519234358.png" alt="image-20210519234358147"></p>
<p>synchronized可见性体现在：进入synchronized代码块后，会清除线程工作内存中的变量，使用变量时不会直接从线程本地内存获取，而是直接获取主内存中最新的值。退出synchronized块时，会将所有对共享变量的修改刷新到主内存中。</p>
<h2 id="四、synchronized的缺陷"><a href="#四、synchronized的缺陷" class="headerlink" title="四、synchronized的缺陷"></a>四、synchronized的缺陷</h2><p>synchronized锁的主要缺陷是不够灵活，体现在下面几个方面。</p>
<ol>
<li>锁的释放情况少。synchronized监视器锁在方法或代码块正常退出和异常时释放锁。</li>
<li>试图获得锁时不能设置超时、不能中断一个正在试图获得锁的线程。</li>
<li>相对于读写锁，加锁和释放的时机单一，每个锁只有单一条件（锁定某个对象），可能不够。</li>
<li>无法知道是否成功获取到锁。例如Lock的tryLock方法</li>
</ol>
<h2 id="五、快问快答"><a href="#五、快问快答" class="headerlink" title="五、快问快答"></a>五、快问快答</h2><h3 id="1-使用synchronized的注意点"><a href="#1-使用synchronized的注意点" class="headerlink" title="1 使用synchronized的注意点"></a>1 使用synchronized的注意点</h3><ul>
<li><p>锁对象不能为空，为空会报空指针。其次对象头存储锁标识，如果为空了，也无法存储。</p>
</li>
<li><p>作用域（临界区）不宜过大。范围过大，相当于串行化部分较大，影响并发效率。</p>
</li>
</ul>
<h3 id="2-如何选择Lock和synchronized关键字"><a href="#2-如何选择Lock和synchronized关键字" class="headerlink" title="2 如何选择Lock和synchronized关键字"></a>2 如何选择Lock和synchronized关键字</h3><p>大原则是避免出错。优先使用java.util.concurrent包下的现成工具类；其次采用synchronized关键字；当使用到Lock特性（例如灵活加解锁）时，才使用Lock锁。</p>
<h3 id="3-synchronized性能较差，如何提升性能"><a href="#3-synchronized性能较差，如何提升性能" class="headerlink" title="3 synchronized性能较差，如何提升性能"></a>3 synchronized性能较差，如何提升性能</h3><ol>
<li>优化使用范围，满足需求的情况下，临界区尽可能小</li>
<li>使用其他类型加锁，例如读写锁。</li>
</ol>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">dtyy</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://dtyytop.gitee.io/2020/05/15/devnotes/zhi-mian-java/bing-fa/bing-fa-he-xin/2.2-synchronized-guan-jian-zi/">https://dtyytop.gitee.io/2020/05/15/devnotes/zhi-mian-java/bing-fa/bing-fa-he-xin/2.2-synchronized-guan-jian-zi/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://dtyytop.gitee.io" target="_blank">Reality</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Java%E5%86%85%E5%AD%98%E6%A8%A1%E5%9E%8B/">Java内存模型</a><a class="post-meta__tags" href="/tags/synchronized/">synchronized</a></div><div class="post_share"><div class="social-share" data-image="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222615.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button button--animated"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://gitee.com/dtyytop/blogimage/raw/master/img/20210515001034.png" target="_blank"><img class="post-qr-code-img" src="https://gitee.com/dtyytop/blogimage/raw/master/img/20210515001034.png" alt="wechat"/></a><div class="post-qr-code-desc">wechat</div></li><li class="reward-item"><a href="https://gitee.com/dtyytop/blogimage/raw/master/img/20210515001009.png" target="_blank"><img class="post-qr-code-img" src="https://gitee.com/dtyytop/blogimage/raw/master/img/20210515001009.png" alt="alipay"/></a><div class="post-qr-code-desc">alipay</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2020/05/15/devnotes/zhi-mian-java/jdk-yuan-ma-fen-xi/3-hashmap-yuan-ma-fen-xi/"><img class="prev-cover" src="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222600.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">JDK8 HashMap源码分析</div></div></a></div><div class="next-post pull-right"><a href="/2020/05/17/devnotes/zhi-mian-java/jdk-yuan-ma-fen-xi/2-linkedlist-yuan-ma-fen-xi-yu-mian-shi-ti/"><img class="next-cover" src="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222646.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">LinkedList源码分析以及与ArrayList的区别</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="card-info-avatar is-center"><img class="avatar-img" src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/><div class="author-info__name">dtyy</div><div class="author-info__description">Java全栈</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">95</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">28</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">16</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://gitee.com/dtyytop"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://gitee.com/dtyytop" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="mailto:1607961042@qq.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%80%E3%80%81synchronized%E7%9A%84%E4%B8%A4%E7%A7%8D%E7%94%A8%E6%B3%95%EF%BC%9A%E5%AF%B9%E8%B1%A1%E9%94%81%E5%92%8C%E7%B1%BB%E9%94%81"><span class="toc-number">1.</span> <span class="toc-text">一、synchronized的两种用法：对象锁和类锁</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-1-%E5%AF%B9%E8%B1%A1%E9%94%81"><span class="toc-number">1.1.</span> <span class="toc-text">1.1 对象锁</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-2-%E7%B1%BB%E9%94%81"><span class="toc-number">1.2.</span> <span class="toc-text">1.2 类锁</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-3-%E8%B0%83%E8%AF%95%E6%8A%80%E5%B7%A7-%E2%80%93-%E6%9F%A5%E7%9C%8B%E7%BA%BF%E7%A8%8B%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F"><span class="toc-number">1.3.</span> <span class="toc-text">1.3 调试技巧 – 查看线程生命周期</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-4-%E5%A4%9A%E7%BA%BF%E7%A8%8B%E8%AE%BF%E9%97%AE%E5%90%8C%E6%AD%A5%E6%96%B9%E6%B3%95%E7%9A%847%E7%A7%8D%E6%83%85%E5%86%B5"><span class="toc-number">1.4.</span> <span class="toc-text">1.4 多线程访问同步方法的7种情况</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%80%BB%E7%BB%93"><span class="toc-number">1.4.1.</span> <span class="toc-text">总结</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BA%8C%E3%80%81synchronized%E7%9A%84%E6%80%A7%E8%B4%A8"><span class="toc-number">2.</span> <span class="toc-text">二、synchronized的性质</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#2-1-%E5%8F%AF%E9%87%8D%E5%85%A5%E6%80%A7%E8%B4%A8"><span class="toc-number">2.1.</span> <span class="toc-text">2.1 可重入性质</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-2-%E4%B8%8D%E5%8F%AF%E4%B8%AD%E6%96%AD%E6%80%A7%E8%B4%A8"><span class="toc-number">2.2.</span> <span class="toc-text">2.2 不可中断性质</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%89%E3%80%81synchronized%E5%BA%95%E5%B1%82%E5%8E%9F%E7%90%86"><span class="toc-number">3.</span> <span class="toc-text">三、synchronized底层原理</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#3-1-%E5%86%85%E7%BD%AE%E9%94%81%E4%B8%8E%E7%AD%89%E4%BB%B7Lock%E5%BD%A2%E5%BC%8F%E4%BB%A3%E7%A0%81"><span class="toc-number">3.1.</span> <span class="toc-text">3.1 内置锁与等价Lock形式代码</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-2-%E5%8F%AF%E9%87%8D%E5%85%A5%E5%8E%9F%E7%90%86"><span class="toc-number">3.2.</span> <span class="toc-text">3.2 可重入原理</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B7%B1%E5%85%A5JVM%E7%9C%8B%E5%AD%97%E8%8A%82%E7%A0%81%E2%80%93%E4%BB%85%E5%90%8C%E6%AD%A5%E4%BB%A3%E7%A0%81%E5%9D%97"><span class="toc-number">3.2.1.</span> <span class="toc-text">深入JVM看字节码–仅同步代码块</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%90%86%E8%A7%A3monitorenter%E5%92%8Cmonitorexit%E6%8C%87%E4%BB%A4"><span class="toc-number">3.2.2.</span> <span class="toc-text">理解monitorenter和monitorexit指令</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-3-%E5%8F%AF%E8%A7%81%E6%80%A7%E5%8E%9F%E7%90%86"><span class="toc-number">3.3.</span> <span class="toc-text">3.3 可见性原理</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%9B%9B%E3%80%81synchronized%E7%9A%84%E7%BC%BA%E9%99%B7"><span class="toc-number">4.</span> <span class="toc-text">四、synchronized的缺陷</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BA%94%E3%80%81%E5%BF%AB%E9%97%AE%E5%BF%AB%E7%AD%94"><span class="toc-number">5.</span> <span class="toc-text">五、快问快答</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-%E4%BD%BF%E7%94%A8synchronized%E7%9A%84%E6%B3%A8%E6%84%8F%E7%82%B9"><span class="toc-number">5.1.</span> <span class="toc-text">1 使用synchronized的注意点</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-%E5%A6%82%E4%BD%95%E9%80%89%E6%8B%A9Lock%E5%92%8Csynchronized%E5%85%B3%E9%94%AE%E5%AD%97"><span class="toc-number">5.2.</span> <span class="toc-text">2 如何选择Lock和synchronized关键字</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-synchronized%E6%80%A7%E8%83%BD%E8%BE%83%E5%B7%AE%EF%BC%8C%E5%A6%82%E4%BD%95%E6%8F%90%E5%8D%87%E6%80%A7%E8%83%BD"><span class="toc-number">5.3.</span> <span class="toc-text">3 synchronized性能较差，如何提升性能</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2021/06/02/devnotes/ji-qun-yan-jin/nginx/1.3-nginx-jin-cheng-mo-xing-yu-shi-jian-chu-li-ji-zhi/" title="Nginx进程模型"><img src="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222600.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Nginx进程模型"/></a><div class="content"><a class="title" href="/2021/06/02/devnotes/ji-qun-yan-jin/nginx/1.3-nginx-jin-cheng-mo-xing-yu-shi-jian-chu-li-ji-zhi/" title="Nginx进程模型">Nginx进程模型</a><time datetime="2021-06-01T16:00:00.000Z" title="发表于 2021-06-02 00:00:00">2021-06-02</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/06/02/devnotes/ji-qun-yan-jin/nginx/1.4-nginx-he-xin-wen-jian-jie-gou-fen-xi/" title="Nginx核心配置结构"><img src="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222629.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Nginx核心配置结构"/></a><div class="content"><a class="title" href="/2021/06/02/devnotes/ji-qun-yan-jin/nginx/1.4-nginx-he-xin-wen-jian-jie-gou-fen-xi/" title="Nginx核心配置结构">Nginx核心配置结构</a><time datetime="2021-06-01T16:00:00.000Z" title="发表于 2021-06-02 00:00:00">2021-06-02</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/05/30/devnotes/ji-qun-yan-jin/nginx/1.2-wei-shi-me-xuan-ze-nginx/" title="集群、代理与Nginx"><img src="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222629.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="集群、代理与Nginx"/></a><div class="content"><a class="title" href="/2021/05/30/devnotes/ji-qun-yan-jin/nginx/1.2-wei-shi-me-xuan-ze-nginx/" title="集群、代理与Nginx">集群、代理与Nginx</a><time datetime="2021-05-29T16:00:00.000Z" title="发表于 2021-05-30 00:00:00">2021-05-30</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/05/30/devnotes/ji-qun-yan-jin/redis/redis-zhu-cong-fu-zhi-yu-yuan-li/" title="Redis主从复制架构与原理"><img src="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222646.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Redis主从复制架构与原理"/></a><div class="content"><a class="title" href="/2021/05/30/devnotes/ji-qun-yan-jin/redis/redis-zhu-cong-fu-zhi-yu-yuan-li/" title="Redis主从复制架构与原理">Redis主从复制架构与原理</a><time datetime="2021-05-29T16:00:00.000Z" title="发表于 2021-05-30 00:00:00">2021-05-30</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/05/30/devnotes/ji-qun-yan-jin/redis/redis-chi-jiu-hua-ji-zhi/" title="Redis的两种持久化机制"><img src="https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222634.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Redis的两种持久化机制"/></a><div class="content"><a class="title" href="/2021/05/30/devnotes/ji-qun-yan-jin/redis/redis-chi-jiu-hua-ji-zhi/" title="Redis的两种持久化机制">Redis的两种持久化机制</a><time datetime="2021-05-29T16:00:00.000Z" title="发表于 2021-05-30 00:00:00">2021-05-30</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('https://gitee.com/dtyytop/blogimage/raw/master/img/cover/20210525222615.jpg')"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2021 By dtyy</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="font-plus" type="button" title="放大字体"><i class="fas fa-plus"></i></button><button id="font-minus" type="button" title="缩小字体"><i class="fas fa-minus"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="/js/search/local-search.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"></div><script defer="defer" id="ribbon" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-ribbon.min.js" size="150" alpha="0.6" zIndex="-1" mobile="false" data-click="false"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = true;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>